package main

import (
	"fmt"
	"strconv"

	"github.com/beevik/etree"
)

func ParseUi(file string) (*WindowUi, *etree.Element, error) {
	doc := etree.NewDocument()
	err := doc.ReadFromFile(file)
	if err != nil {
		return nil, nil, err

	}
	uiroot := doc.SelectElement("ui")
	if uiroot == nil {
		return nil, nil, fmt.Errorf("not found ui")
	}
	mainwindow := uiroot.SelectElement("widget")
	if mainwindow == nil {
		return nil, nil, fmt.Errorf("not found widget")
	}
	if mainwindow.SelectAttr("class").Value != "QMainWindow" {
		panic("mainwindow is not a QMainWindow")
	}
	var windowui WindowUi
	// 读取property
	prop := mainwindow.SelectElements("property")

	for _, v := range prop {
		protname := v.SelectAttr("name").Value
		switch protname {
		case "windowTitle":
			windowui.Property.Title = v.SelectElement("string").Text()
		case "geometry":
			windowui.Property.X, _ = strconv.Atoi(v.SelectElement("rect").SelectElement("x").Text())
			windowui.Property.Y, _ = strconv.Atoi(v.SelectElement("rect").SelectElement("y").Text())
			windowui.Property.Width, _ = strconv.Atoi(v.SelectElement("rect").SelectElement("width").Text())
			windowui.Property.Height, _ = strconv.Atoi(v.SelectElement("rect").SelectElement("height").Text())
		}
	}
	windowui.Property.Ele = prop

	// 读取menu
	// 先获取action
	actions := mainwindow.SelectElements("action")
	// 获取menu
	menubar := GetWidgetByClass(mainwindow, "QMenuBar")
	//menus := GetWidgetsByClass(menubar, "QMenu")
	var menu []*Menu
	menu = AddMenu(menubar, actions, menu)
	windowui.Menu = menu

	centralwidget := GetWidgetByName(mainwindow, "centralwidget")
	var windowui_ele []*WindowUiElement
	windowui_ele, err = AddWidgets(centralwidget, windowui_ele, nil)
	if err != nil {
		return nil, nil, err
	}
	windowui.Elements = windowui_ele

	// to json格式化输出
	//json_data, _ := json.MarshalIndent(windowui, "", "  ")
	//fmt.Println(string(json_data))
	// 写入json文件
	/*file, err := os.Create("widget.json")
	if err != nil {
		panic(err)
	}
	defer file.Close()
	file.Write(json_data)
	file.Sync()
	fmt.Println("write json success")*/

	return &windowui, &doc.Element, nil
}
